<script setup>
import { ref, onMounted, nextTick } from "vue"; // 添加 nextTick
import * as echarts from "echarts";
import "echarts-extension-amap";
import mapJson from "./map.json";
// 模拟数据
const mapData = [
  { name: "渝北区", value: 1, category1: 1, category2: 1 },
  { name: "长寿区", value: 2, category1: 2, category2: 2 },
  { name: "南岸区", value: 3, category1: 3, category2: 3 },
  { name: "巴南区", value: 4, category1: 4, category2: 4 },
  { name: "江北区", value: 5, category1: 5, category2: 5 },
  { name: "渝中区", value: 6, category1: 6, category2: 6 },
  { name: "九龙坡区", value: 7, category1: 7, category2: 7 },
  // 其他区域数据...
];
const option = {
  tooltip: {
    trigger: "item",
    formatter: (params) => {
      return `${params.name}<br/>类别一：${
        params.data?.category1 || 0
      }个<br/>类别二：${params.data?.category2 || 0}个`;
    },
  },
  visualMap: {
    min: 0,
    max: 5,
    left: "5%",
    bottom: "5%",
    calculable: true,
    seriesIndex: [0],
    inRange: {
      color: ["#0C2E79", "#0444AD", "#0665FF"],
    },
    textStyle: {
      color: "#fff",
    },
  },
  geo: {
    map: "重庆",
    label: {
      show: true,
      color: "#fff",
      fontSize: 12,
    },
    itemStyle: {
      areaColor: "#0C2E79",
      borderColor: "#0665FF",
      borderWidth: 1,
    },
    emphasis: {
      itemStyle: {
        areaColor: "#0444AD",
        shadowBlur: 10,
        shadowColor: "rgba(6, 101, 255, 0.5)",
      },
    },
  },
  series: [
    {
      name: "风险指数",
      type: "map",
      geoIndex: 0,
      data: mapData,
    },
  ],
};

// 添加点击事件处理函数
const handleMapClick = (params) => {
  const regionName = params.name;
  const regionData = mapData.find((data) => data.name === regionName);
  if (regionData) {
    showModal.value = true;
    selectedRegion.value = regionData;
  }
};

onMounted(async () => {
  echarts.registerMap("重庆", mapJson);

  // 确保地图数据加载完成后再初始化图表
  if (mapJson) {
    await nextTick(); // 确保 DOM 已经更新
    initChart(option);
  }
});

// 弹窗状态管理
const showModal = ref(false);
const selectedRegion = ref(null);

function initChart(option) {
  const chartDom = document.getElementById("myChart");
  const myChart = echarts.init(chartDom);
  myChart.setOption(option);
  myChart.on("click", handleMapClick);
}
</script>
<template>
  <div id="myChart" class="myChart"></div>
</template>
<style lang="scss" scoped>
.myChart {
        width: 500px;
        height: 500px;
      }
</style>